﻿using System.Web.Mvc;
using System.Linq;
using System;

namespace SlamCms.Web.Mvc
{
	public class SeparatedValuesModelBinder : IModelBinder
	{
		public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
		{
			string value = null;

			if (controllerContext.RouteData.Values[bindingContext.ModelName] != null)
				value = controllerContext.RouteData.Values[bindingContext.ModelName].ToString();
			else if (controllerContext.HttpContext.Request[bindingContext.ModelName] != null)
				value = controllerContext.HttpContext.Request[bindingContext.ModelName];

			if (value == null)
				return null;

			var values = value.Split("/,".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

			if (bindingContext.ModelType == typeof(int[]))
				return values.Select(v => Convert.ToInt32(v)).ToArray();
			else if (bindingContext.ModelType == typeof(float[]))
				return values.Select(v => Convert.ToSingle(v)).ToArray();
			else if (bindingContext.ModelType == typeof(double[]))
				return values.Select(v => Convert.ToDouble(v)).ToArray();
			else if (bindingContext.ModelType == typeof(string[]))
				return values;

			return null;
		}
	}
}